How to use square bracket([]) Notation In Typescript
In this approach, we are using square bracket([]) Notation to access the private members of the Class. We have defined the private variable as data3 and the private function as privateFn in GFGClass3. We are accessing this member using [] notation and type assertion to any.
Syntax:
const value = (object as any)['propertyName'];
Example: Below is the implementation of the above-discussed approach.
class GFGClass3 {
private data3: string =
'This is Private Variable';
private privateFn(): void {
console.log(
'This is Private Function Called');
}
public accessFn3() {
const privateVar =
(this as any)['data3'];
console.log(privateVar);
const privateFunction =
(this as any)['privateFn'];
privateFunction.call(this);
}
}
const myObject = new GFGClass3();
myObject.accessFn3();
Output:
"This is Private Variable"
"This is Private Function Called"
How to Access TypeScript Private Members ?
In this TypeScript article, we will learn how to access the TypeScript private members using different approaches. We can interact with the encapsulated components within the class and access them in the application.
There are three different approaches through which we can access TypeScript private members.
Table of Content
- Using any Type
- Using Reflect
- Using square bracket([]) Notation
- Using ES6 WeakMap